package com.linked.store.box.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import com.linked.store.box.bean.param.AddBoxInfoParam;
import com.linked.store.box.bean.param.BoxPageParam;
import com.linked.store.box.bean.param.ThingEnchaseParam;
import com.linked.store.box.bean.po.BoxInfoPO;
import com.linked.store.box.bean.vo.BoxPageVO;
import com.linked.store.box.service.IBoxHandleService;
import com.linked.store.config.FileDirConfig;
import com.linked.store.util.MinioUtils;
import com.linked.store.util.PdfUtils;
import com.linked.store.util.QRBarCodeUtil;
import com.linked.store.util.SystemUtils;
import com.linked.universal.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.List;

/**
 * @author :dbq
 * @date : 2023/3/17 10:52+
 * @description : desc
 */
@RestController
@RequestMapping("boxhandle")
@Slf4j
public class BoxHandleController {

    private final ObjectMapper mapper;

    private final IBoxHandleService boxHandleService;

    private final FileDirConfig dirConfig;

    private final MinioUtils minioUtils;

    @Autowired
    public BoxHandleController(ObjectMapper mapper, IBoxHandleService boxHandleService, FileDirConfig dirConfig, MinioUtils minioUtils) {
        this.mapper = mapper;
        this.boxHandleService = boxHandleService;
        this.dirConfig = dirConfig;
        this.minioUtils = minioUtils;
    }

    @PostMapping("queryBoxPage")
    Result queryBoxPage(@RequestBody BoxPageParam para) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("查询收纳箱页面接口 入参：{}", mapper.writeValueAsString(para));
        }

        IPage<BoxPageVO> boxPage = null;
        try {
            boxPage = boxHandleService.queryBoxPage(para);
        } catch (Exception e) {
            log.error("查询收纳箱页面接口 异常！", e);
            return Result.error("出现未知错误，请联系管理员");
        }

        return boxPage != null ? Result.success(boxPage) : Result.ok(false, "未查询到数据！");
    }

    @PostMapping("addBoxInfo")
    Result addBoxInfo(@RequestBody AddBoxInfoParam param) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("添加收纳箱接口 入参：{}", mapper.writeValueAsString(param));
        }
        boolean ret = false;
        try {
            ret = boxHandleService.addBoxInfo(param);
        } catch (Exception e) {
            log.error("添加收纳箱接口 异常", e);
            return Result.error("出现未知错误，请联系管理员");
        }
        return ret ? Result.success() : Result.ok(false, "添加失败！");
    }

    @PostMapping("thingEnchase")
    Result thingEnchase(@RequestBody ThingEnchaseParam param) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("物品装箱接口 入参：{}", mapper.writeValueAsString(param));
        }
        boolean ret = false;
        try {
            ret = boxHandleService.thingEnchase(param);
        } catch (Exception e) {
            log.error("物品装箱接口 异常", e);
            return Result.error("出现未知错误，请联系管理员");
        }
        return ret ? Result.success() : Result.ok(false, "添加失败！");
    }

    @PostMapping("printBoxInfo")
    Result printBoxInfo(String boxId) throws Exception {
        if (log.isInfoEnabled()) {
            log.info("打印收纳箱信息接口 入参：" + boxId);
        }
        /**
         * 文件上传minio服务器
         * */
        String url = null;
        String pdfDir = null;
        String localDir = null;
        BoxInfoPO boxInfo = null;
        try {
            if (SystemUtils.isLinux()) {
                pdfDir = dirConfig.getLinuxUrl();
            }
            if (SystemUtils.isWindows()) {
                pdfDir = dirConfig.getWindowsUrl();
            }
            File myFilePath = new File(pdfDir);
            if (!myFilePath.exists()) {
                myFilePath.mkdir();
            }
            boxInfo = boxHandleService.findBoxInfo(boxId);
            //生成pdf
            localDir = boxDataToPdf(boxInfo, pdfDir);
        } catch (Exception e) {
            log.error("生成pdf异常！", e);
            return Result.error("出现未知错误，请联系管理员");
        }
        String finalUrl = pdfDir + boxInfo.getBoxId() + "_watermark.pdf";
        try {
            PdfUtils.addWaterMark(localDir, finalUrl, "Bluerain", 40, 50, 10);
        } catch (Exception e) {
            log.error("加水印异常！", e);
        }

        try {
            url = minioUtils.uploadFile(new File(finalUrl), "box_info");
        } catch (Exception e) {
            log.error("上传minio异常！", e);
            return Result.error("出现未知错误，请联系管理员");
        }
        try {
            Path rmFile = Paths.get(localDir);
            if (rmFile != null) {
                Files.delete(rmFile);
            }
        } catch (Exception e) {
            log.error("删除文件异常！", e);
        }
        try {
            Path rmFile = Paths.get(finalUrl);
            if (rmFile != null) {
                Files.delete(rmFile);
            }
        } catch (Exception e) {
            log.error("删除文件异常！", e);
        }

        return StringUtils.isEmpty(url) ? Result.ok(false, "打印失败") : Result.success(url);
    }

    private String boxDataToPdf(BoxInfoPO boxInfo, String dir) throws Exception {
        String localUrl = dir + boxInfo.getBoxId() + ".pdf";

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String currentTime = LocalDateTime.now().format(formatter);


        Document document = new Document();
        //pdf大小：8cm*8cm
        document.setPageSize(new Rectangle(170f, 170f));
        document.setMargins(10, 10, 10, 10);

        FileOutputStream outputStream = new FileOutputStream(localUrl);
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);
        document.open();

        //中文字体,解决中文不能显示问题
        BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

        Font font = new Font(bfChinese, 6, Font.NORMAL);
        Font font_num = new Font(bfChinese, 40, Font.NORMAL);
        //生成二维码
        QRBarCodeUtil.createCodeToFile(boxInfo.getBoxId(), new File(dir), boxInfo.getBoxId() + ".png");
        //二维码
        Image image = Image.getInstance(dir + boxInfo.getBoxId() + ".png");
        //设置图片的宽度和高度
        image.scaleAbsolute(35f, 35f);
        document.add(image);

        Paragraph boxNamePara = new Paragraph("箱名：" + boxInfo.getBoxName(), font);
        document.add(boxNamePara);

//        if (!StringUtils.isEmpty(boxInfo.getBoxLabel())) {
//            Paragraph boxLabelPara = new Paragraph("标签：" + boxInfo.getBoxLabel(), font);
//            document.add(boxLabelPara);
//        }

        if (!StringUtils.isEmpty(boxInfo.getBoxRemarks())) {
            Paragraph boxRemarksPara = new Paragraph("备注：" + boxInfo.getBoxRemarks(), font);
            document.add(boxRemarksPara);
        }

        //删除生成得二维码
        try {
            Path rmFile = Paths.get(dir + boxInfo.getBoxId() + ".png");
            if (rmFile != null) {
                Files.delete(rmFile);
            }
        } catch (Exception e) {
            log.error("删除二维码文件异常！", e);
        }
        //关闭文档
        if (document != null) {
            document.close();
        }
        //关闭书写器
        if (writer != null) {
            writer.close();
        }
        outputStream.close();
        return localUrl;
    }
}
